<?php
namespace Poster\Controller;
use Admin\Controller\InitController;
if (!defined('MODULE_CACHE')) define('MODULE_CACHE', DATA_PATH.'caches_poster/');
class PosterController extends InitController{
	public function _initialize(){
		parent::_initialize();
		$this->db = D('Poster');
		$this->siteid = I('siteid','1','intval');
		$this->space_db = D('PosterSpace');
	}
	public function init(){
		$pagecurr = max(1,I('page',0,'intval'));
		$pagesize = 10;
		$spaceid = (int) I('spaceid');
		$sqlMap = array();
		$sqlMap['spaceid'] = $spaceid;
		$poster_count = $this->db->where($sqlMap)->count();
		$poster_lists = $this->db->where($sqlMap)->page($pagecurr,$pagesize)->select();
		$pages = page($poster_count,$pagesize);
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\''.U('PosterSpace/add').'\', title:\''.L('add_space').'\', width:\'540\', height:\'320\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_space'));
		$format = new \Common\Library\format();
		include $this->admin_tpl('poster_list');
	}
	/**
	 * 添加广告
	 */
	public function add(){
		if(submitcheck('dosubmit')){
			$poster = I('poster');
			$setting = I('setting');
			$setting = $this->check_setting($setting, $poster['type']);
			if($poster['type'] == 'text'){
				$setting['code'] = htmlspecialchars_decode($setting['code']);
			}
			$poster['siteid'] = $this->siteid;
			$poster['setting'] = array2string($setting);
			$poster['addtime'] = NOW_TIME;
			$poster['startdate'] = strtotime($poster['startdate']);
			$poster['enddate'] = strtotime($poster['enddate']);
			$r = $this->create_js($poster['spaceid']);;
			$result = $this->db->update($poster);
			if($result){
				$sqlMap = array();
				$sqlMap['spaceid'] = $poster['spaceid'];
				$sqlMap['siteid'] = $this->siteid;
				$rs = 	$this->space_db->where($sqlMap)->setInc('items',1);
				$this->create_js($poster['spaceid']);
				if(!$rs){
					$this->error('操作失败');
				}else{
					$this->success('操作成功');
				}
			}
		}else{
			$spaceid = (int) I('spaceid');
			$types = get_types();
			$sinfo = $this->space_db->where(array('spaceid'=>$spaceid,'siteid'=>$this->siteid))->field('name,type')->find();
			$setting = $this->get_setting($sinfo['type']);
			$default = count($setting)>0 ? L('please_select').'&nbsp;&nbsp;&nbsp;&nbsp;' : '';
			$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\''.U('PosterSpace/add').'\', title:\''.L('add_space').'\', width:\'540\', height:\'320\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_space'));
			$form = new \Common\Library\form();
			include $this->admin_tpl('poster_add');
		}
	}
	/**
	 * 修改广告
	 * @param $id 为广告id
	 */
	public function edit($id = 0){
		$id = (int) $id;
		$spaceid = (int) I('spaceid');
		$siteid = $this->siteid;
		if($id < 0 ){$this->error('参数错误');}
		if(submitcheck('dosubmit')){
			$poster = I('poster');
			$setting = I('setting');
			$poster['startdate'] = strtotime($poster['startdate']);
			$poster['enddate'] = strtotime($poster['enddate']);
			$setting = $this->check_setting($setting,$poster['type']);
			if($poster['type'] == 'text'){
				$setting['code'] = htmlspecialchars_decode($setting['code']);
			}
			$poster['setting'] = array2string($setting);
			$result = $this->db->where(array('id'=>$id,'siteid'=>$siteid))->save($poster);
			$r = $this->create_js($spaceid);
			if(!$result){
				$this->error('操作失败');
			}
			$this->success("广告修改成功");
		}else{
			$info = $this->db->where(array('id'=>$id,'siteid'=>$siteid))->find();
			$info['setting'] = string2array($info['setting']);
			//查询广告类型
			$sinfo = $this->space_db->where(array('spaceid'=>$info['spaceid'],'siteid'=>$siteid))->field('name,type')->find();
			//根据查出的版位id 查出版位的类型  名称
			$space_type = $this->space_db->getFieldBySpaceid($info['spaceid'],'type');
			$space_name = $this->space_db->getFieldBySpaceid($info['spaceid'],'name');
			$setting = $this->get_setting($space_type);
			$types = get_types();
			$default = count($setting)>0 ? L('please_select').'&nbsp;&nbsp;&nbsp;&nbsp;' : '';
			$form = new \Common\Library\form();
			$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\''.U('PosterSpace/add').'\', title:\''.L('add_space').'\', width:\'540\', height:\'320\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_space'));
			include $this->admin_tpl('poster_edit');
		}
	}
	/**
	 * 广告统计
	 */
	public function stat(){
		$id = (int) I('id');
		//根据id查出广告版块id   spaceid
		$spaceid = $this->db->getFieldById($id,'spaceid');
		if(!$id){$this->error('参数错误');}
		//如果设置了日期查询，设置查询的开始时间和结束时间
		$this->poster_stat = D('PosterStat');
		$year = date('Y',NOW_TIME);
		$month = date('m',NOW_TIME);
		$day = date('d',NOW_TIME);
		$where = $group = $order = '';
		$fields = '*';
		$where = "`pid` = '$id' and `siteid` = '$this->siteid'";
		$range = I('getrange');
		if ($range == 2) { //昨天的统计
			$fromtime = mktime(0, 0, 0, $month, $day-2, $year);
			$totime = mktime(0, 0, 0, $month, $day-1, $year);
			$where .= " AND `clicktime`>='".$fromtime."'";
			$where .= " AND `clicktime`<='".$totime."'";
		} elseif(is_numeric($range)) { //如果设置了查询的天数
			$fromtime = mktime(0, 0, 0, $month, $day-$range, $year);
			$where .= " AND `clicktime`>='".$fromtime."'";
		}
		$order = '`clicktime` DESC';
		//如果为点击、展示统计
		$click = I('get.click');
		$click = isset($click) ? intval($click) : 0;		
		if(is_numeric($click)){
			$click = intval($click);
			$where .= " and `type` = '$click'";
			
			//如果设置了地区 iP 分类
			$group = I('get.group');
			if($group){
				$fields = "*,count($group) as num";
				$order = "`num` DESC";
			}
			$r = $this->poster_stat->where($where)->field('count(*) as num')->group($group)->find();
		}else{
			$r = $this->poster_stat->where($where)->field('count(*) as num')->find();
		}
		
		$page = max(1,I('page',0,'intval'));
		$pagecurr =  20;
		$count = $this->poster_stat->where($where)->count();
		$data = $this->poster_stat->where($where)->page($page,$pagecurr)->field($fields)->order($order)->select();
		$pages = page($count,$pagecurr);
		//获取历史下拉框，有历史数据查询时，会自动换表
		$selectstr = $this->poster_stat->get_list($_GET['year']);
		//echo $selectstr;
		unset($r);
		$format = new \Common\Library\format();
		include $this->admin_tpl('poster_stat');
	}
	/**
	 * 广告排序
	 */
	public function listorder($listorder = array()){
		$listorders = (array) $listorder;
		if(empty($listorders)){$this->error('参数错误');}
		if(is_array($listorders) && !empty($listorders)){
			$sqlMap = array();
			foreach ($listorders as $k=>$v) {
				$sqlMap['listorder'] = $v;
				$this->db->where(array('id'=>$k))->save($sqlMap);			
			}
			$this->success('操作成功');
		}
	}
	/**
	 * 广告启用 、停用  0为启用  1为停用
	 */
	public function public_approval($id = 0){
		$id = (array) $id;
		$passed = (int) I('get.passed');
		if($passed < 0 || empty($id) && !is_array($id)){
			$this->error(L('illegal_parameters'));
		}
		$sqlMap = array();
		$sqlMap['disabled'] = $passed;
		$result = $this->db->where(array('id'=>array('in',$id),'siteid'=>$this->siteid))->save($sqlMap);
		$spaceid = (int) I('get.spaceid');
		if($passed == 0){//启用时
			$this->create_js($spaceid);
		}
		if(!$result){
			$this->error('操作失败');
		}
		$this->success('操作成功');
	}
	/**
	 * 删除广告
	 */
	public function delete($id = 0){
		$ids = (array) $id;
		if(empty($ids) && !is_array($ids)){
			$this->error('参数错误');
		}
		foreach($ids as $id){
			$id = (int) $id;
			$spaceid = $this->db->getFieldById($id,'spaceid');
			$this->space_db->where(array('spaceid'=>$spaceid,'siteid'=>$this->siteid))->setDec('items',count($ids));
			$result = $this->db->where(array('id'=>$id,'siteid'=>$this->siteid))->delete();
		}
		if(!$result){
			$this->error('操作失败');
		}
		$this->success('操作成功');
	}
	/**
	 * ajax检查广告名的合法性
	 */
	public function public_check_poster(){
		$name = I('name');
		if(!$name){exit(0);}
		if (CHARSET=='gbk') {
			$name = safe_replace(iconv('UTF-8', 'GBK', $name));
		}
		if($name){
			$spaceid = (int) I('spaceid');
			$r = $this->db->where(array('spaceid'=>$spaceid))->find();
			if($r['name'] == $name){
				exit('1');
			}
		}
		$r = $this->db->where(array('siteid'=>$this->siteid,'name'=>$name))->field('id')->find();
		if($r['id']){
			exit('0');
		}else{
			exit('1');
		}
	}
	/**
	 * 根据版位的类型，得到版位的配置信息。如广告类型等
	 * @param string  $type 版位的类型,默认情况下是一张图片或者动画
	 * return boolean
	 */
	private function get_setting($type) {
		$data = $poster_template = array();
		$poster_template = getcache('poster_template_'.$this->siteid, 'commons');
		if (is_array($poster_template) && !empty($poster_template)) {
			$data = $poster_template[$type];
		} else {
			switch($type) {
				case 'banner':
					$data['type'] = array('images' => L('photo'), 'flash' => L('flash'));
					$data['num'] = 1;
					break;
	
				case 'fixure':
					$data['type'] = array('images' => L('photo'), 'flash' => L('flash'));
					$data['num'] = 1;
					break;
	
				case 'float':
					$data['type'] = array('images' => L('photo'), 'flash' => L('flash'));
					$data['num'] = 1;
					break;
	
				case 'couplet':
					$data['type'] = array('images' => L('photo'), 'flash' => L('flash'));
					$data['num'] = 2;
					break;
						
				case 'imagechange':
					$data['type'] = array('images' => L('photo'));
					$data['num'] = 1;
					break;
						
				case 'imagelist':
					$data['type'] = array('images' => L('photo'));
					$data['num'] = 1;
					break;
	
				case 'text':
					$data['type'] = array('text' => L('title'));
					break;
						
				case 'code':
					$data['type'] = array('text' => L('title'));
					break;
						
				default :
					$data['type'] = array('images' => L('photo'), 'flash' => L('flash'));
					$data['num'] = 1;
			}
		}
		return $data;
	}
	/**
	 * 检查广告的内容信息，如图片、flash、文字
	 * @param array $setting
	 * @param string $type 广告的类型
	 * @return array
	 */
	private function check_setting($setting = array(), $type = 'images') {
		switch ($type) {
			case 'images':
				unset($setting['flash'], $setting['text']);
				if(is_array($setting['images'])) {
					$tag = 0;
					foreach ($setting['images'] as $k => $s) {
						if($s['linkurl']=='http://') {
							$setting['images'][$k]['linkurl'] = '';
						}
						if (!$s['imageurl']) unset($setting['images'][$k]);
						else $tag = 1;
					}
					if (!$tag) $this->error(L('no_setting_photo'));
				}
				break;
	
			case 'flash':
				unset($setting['images'], $setting['text']);
				if (is_array($setting['flash'])) {
					$tag = 0;
					foreach ($setting['flash'] as $k => $s) {
						if (!$s['flashurl']) unset($setting['flash'][$k]);
						else $tag = 1;
					}
					if (!$tag) $this->error(L('no_flash_path'));
				}
				break;
					
			case 'text':
				unset($setting['images'], $setting['flash']);
				if ((!isset($setting['text'][1]['title']) || empty($setting['text'][1]['title'])) && (!isset($setting['text']['code']) || empty($setting['text']['code']))) {
					$this->error(L('no_title_info'));
				}
				break;
		}
		return $setting[$type];
	}
	/**
	 * 生成广告js文件
	 * @param intval $id 广告版位ID
	 * @return boolen 成功返回true
	 */
	private function create_js($id = 0) {
		$id = (int) $id;
		if (!$id) {
			$this->msg = L('no_create_js');
			return false;
		}
		$siteid = I('siteid','1','intval');
		$r = $this->space_db->where(array('siteid'=>$siteid, 'spaceid'=>$id))->find();
		$now = NOW_TIME;
		if ($r['setting']) $space_setting = string2array($r['setting']);
		if ($r['type']=='code') return true;
		$poster_template = getcache('poster_template_'.$siteid, 'commons');
		if ($poster_template[$r['type']]['option']) {
			$where = "`spaceid`='".$id."' AND `siteid`='".$siteid."' AND `disabled`=0 AND `startdate`<='".$now."' AND (`enddate`>='".$now."' OR `enddate`=0) ";
			$pinfo = $this->db->where($where)->order('listorder ASC,id DESC')->select();
			if (is_array($pinfo) && !empty($pinfo)) {
				foreach ($pinfo as $k => $rs) {
					if ($rs['setting']) {
						$rs['setting'] = string2array($rs['setting']);
						$pinfo[$k] = $rs;
					} else {
						unset($pinfo[$k]);
					}
				}
				$p_setting = $pinfo[0]['setting'];
				extract($r);
			} else {
				return true;
			}
		} else {
			$where = " `spaceid`='".$id."' AND `siteid`='".$siteid."' AND `disabled`=0 AND `startdate`<='".$now."' AND (`enddate`>='".$now."' OR `enddate`=0)";
			$pinfo = $this->db->where($where)->order('listorder ASC,id DESC')->select();
			if (is_array($pinfo) && !empty($pinfo)) {
				foreach ($pinfo as $k=>$v){
					if($v['setting']){
						$v['setting'] = string2array($v['setting']);
						$pinfo[$k] = $v;
					}else{
						unset($pinfo[$k]);
					}
				}
				$p_setting = $pinfo[0]['setting'];
			}
			extract($r);
			if (!is_array($pinfo) || empty($pinfo)) return true;
			extract($pinfo, EXTR_PREFIX_SAME , 'p');
		}
		$file = SITE_PATH.'/static/js/'.$path;
		ob_start();
		include MODULE_PATH.'Fields'.DIRECTORY_SEPARATOR.$type.'.html';
		$data = ob_get_contents();
		ob_end_clean();
		$stlen = file_put_contents($file, $data);
		
		if(file_exists($file)){
			return true;
		}else{
			return false;
		}
	}
}